﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PNProject.Core;
using PNProject.Core.Converter;
using PNProject.EF;
using System.Web.Security;

namespace PNProject.Controllers
{
    [Authorize]
    public class AdminOneContentController : Controller
    {
        //
        // GET: /OneContent/

        public ActionResult Index()
        {
            List<OneContentModel> result = new List<OneContentModel>();
            var list = StaticData.oneContentRepo.GetAll();
            foreach (var item in list)
            {
                var conv = OneContentConverter.OneContentTo(item);
                result.Add(conv);
            }
            return View(result);
        }

        public ActionResult Detail(string id)
        {
            try
            {
                var newid = int.Parse(id);
                var con = StaticData.oneContentRepo.GetOne(a => a.OneContentID == newid);
                if (con != null)
                {
                    var result = OneContentConverter.OneContentTo(con);
                    return View(result);
                }
                return RedirectToAction("Error", "Admin");
            }
            catch (Exception e)
            {
                return RedirectToAction("Error", "Admin");
            }
            
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Detail(OneContentModel model)
        {
            try
            {
                var dbo = StaticData.oneContentRepo.GetOne(a => a.OneContentID == model.OneContentID);
                if (dbo != null)
                {
                    var copy = OneContentConverter.CopyOneContent(dbo);
                    copy.XContent = model.XContent;
                    StaticData.oneContentRepo.Save(dbo, copy);
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Error", "Admin");
            }
            catch (Exception e)
            {
                return RedirectToAction("Error", "Admin");
            }

            return View();
        }

    }
}
